﻿using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using WWLauncher.Libs.WindowsInput.Native;
using WWLauncher.Util;

namespace WWLauncher
{
    public partial class MainWindow
    {
        private bool threadStopFlg;
        private const int GWL_STYLE = -16;

        private Thread _thread;
        /// <summary>
        /// 特殊的方法
        /// </summary>
        public void Extend()
        {
            _thread = new Thread(() =>
             {
                 //Thread.Sleep(1000);
                 var failures = 0;
                 do
                 {
                     try
                     {
                         Thread.Sleep(500);
                         //Notepad3_x64
                         //
                         var process = Process.GetProcessesByName("RelicCoH2").FirstOrDefault();
                         if (process != null)
                         {
                             IntPtr handle = process.MainWindowHandle;
                             var isMinimized = IsMinimized(handle);
                             KeyUtil.SetState(VirtualKeyCode.CAPITAL, !isMinimized);

                             Config.IsMonitor = isMinimized;


                         }
                         else
                         {
                             failures++;
                             if (failures > 5)
                             {
                                 //关闭大写
                                 KeyUtil.SetState(VirtualKeyCode.CAPITAL, false);
                                 failures = 0;
                                 threadStopFlg = true;
                             }
                         }

                     }
                     catch
                     {
                         // ignored
                     }
                     if (threadStopFlg)
                     {
                         break;
                     }
                 } while (true);
             });
            _thread.Start();
        }

        private bool IsMinimized(IntPtr handle)
        {
            int style = WinApi.GetWindowLong(handle, GWL_STYLE);
            return (style & WinApi.WS_MINIMIZE) == WinApi.WS_MINIMIZE;
        }
    }
}